/**
 * 开始这边的代码很好，只有100来行
 * 后来产品设计的搜索条件和配置毁了这边
 * 尽力在维护了，复用逻辑用hoc包住了，但是hoc要拆细一点嘛？hoc现在已经800行代码了
 * react 15推崇用hoc的方式写复用逻辑，但是hoc是链式的，所以底层hoc很难控制原始component的state，这也是我没拆hoc的原因
 * 如果版本升级，请把hoc按state归属拆成多个hook
 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import DataHoc from "containers/pay/template/data-hoc";
import AdvancedTable from "components/advanced-table";
import { Alert, Button, message, Radio, Spin, Modal, Select, Form } from 'antd';
import { messages } from "share/common";
import paymentService from 'containers/pay/pay-workbench/pay-workbench.service'
import PayModal from 'containers/pay/pay-workbench/unpaid/pay-modal'
import BankHoc from "../../template/bank-hoc";
import Space from "components/space";
import { orderTab, optionsMap, handleOptions } from "../../template/utils"

const { Option } = Select;

@connect(mapStateToProps)
@DataHoc
class Unpaid extends Component {

  key = 'Unpaid';

  state = {
    radioValue: '',
    radioOption: [],
    loading: false,
    payAll: false,
    setOfBookId: '',
    rowSelection: this.props.getSelection(this.props.noticeAlert)(false),
    selectedData: [],
    visible: false,
    buttonDisabled: true,
    tableTitle: [],
    errorAlert: null,
    editCellError: false,
    typeCode: null,
    searchForm: this.props.getSearchForm(this.key),
    searchParams: {},
    bankInfo: undefined,
    sortDTOs: [],
    editing: false
  };

  componentWillMount = () => {
    const { setOfBooksId } = this.props.company;
    this.setState({ loading: true });
    paymentService.getOptions({ setOfBookId: setOfBooksId }).then(res => {
      let radioValue = optionsMap.get(res.data.defPaymentMethods[0]).itemCode;
      this.setState({
        loading: false,
        radioOption: orderTab(handleOptions(res.data.ablePaymentMethods)),
        radioValue,
        payAll: !res.data.isPartPay,
        setOfBookId: setOfBooksId
      })
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  service = (page, pageSize, searchParams) => {
    let { radioValue, setOfBookId, bankInfo, sortDTOs } = this.state, { initConfig } = this.props;
    let params = {
      page, size: pageSize, paymentMethodCategory: radioValue, ...searchParams,
      sortProperty: (sortDTOs[0] || {}).property,
      sortDirection: (sortDTOs[0] || {}).direction
    };
    !params.paymentCompanyId && bankInfo && (params.paymentCompanyId = (bankInfo.paymentAuthCompanyIds || null));
    !params.currencyCode && bankInfo && bankInfo.companyBank && !bankInfo.companyBank.multiCurrencyPay && (params.currencyCode = bankInfo.companyBank.currencyCode);
    return initConfig(this.key, params, searchParams.setOfBookId !== setOfBookId ? searchParams.setOfBookId : '');
  };

  onRadioChange = e => {
    this.setState({ radioValue: e.target.value }, () => {
      this.advancedTableRef.setState({
        pagination: Object.assign(this.advancedTableRef.state.pagination, { current: 1 })
      });
      this.selectorRef.handleFocus();
    });
  };

  handleOk = () => {
    this.setState({ visible: false }, this.handleRefresh);
  };

  editCurrentPay = (value, record) => {
    if (!value || value > record.payableAmount) {
      message.error(messages('finance-4.key171')/*本次支付金额不能大于可支付金额*/);
      return
    }
    let flag = true;
    this.setState({ editCellError: false });
    this.advancedTableRef.state.dataSource.map(item => {
      if (item.id === record.id) {
        flag = item.currentPayAmount === value;
        item.currentPayAmount = value
      }
    });
    if (!flag) {
      this.props.noticeAlert(this.state.selectedData);
      message.success(messages('finance-4.key172')/*修改成功*/)
    }
  };

  editAccount = (key, value, record, selectItem) => {
    let params = { id: record.id, versionNumber: record.versionNumber };
    if (key === 'paymentMethodCategory' && (
        record.paymentMethodCategoryName === value
        || record.accountType === 'ALIPAY_LOGON_ID' && value !== 'ONLINE_PAYMENT'
      )) {
      if (record.paymentMethodCategoryName !== value) {
        message.error(messages('finance-4.key173')/*所选行中有收款账户为支付宝账户的数据,请返回检查*/);
        this.setState({ editCellError: false });
      }
      return ;
    }
    params[key] = value;
    if (key === 'accountNumber'){
      params = Object.assign(params, selectItem);
    }
    this.setState({ editing: true });
    paymentService.updateAccountNum([params]).then(() => {
      message.success(messages('finance-4.key172')/*修改成功*/);
      this.setState({ editCellError: false, editing: false }, () => {
        this.advancedTableRef.getList();
      });
    }).catch(e => {
      this.setState({ editCellError: true, editing: false });
      message.error(e.response.data.message);
    })
  };

  onSearch = (pagination, values) => {
    setTimeout(() => {
      this.setState({ searchParams: values }, () => {
        this.props.onClearSelected(() => this.props.noticeAlert([]));
        this.selectorRef.handleFocus();
      });
    }, 0);
  };

  handleChangeType = () => {
    const { radioOption } = this.state;
    Modal.confirm({
      title: messages('finance-4.key174')/*批量修改付款方式类型为：*/,
      content: <Form.Item
        required
        label={messages('finance-4.key175')/*付款方式类型*/}
        {...{
          labelCol: { span: 10 },
          wrapperCol: { span: 12, offset: 1 },
        }}
      >
        <Select
          onChange={value => this.setState({ typeCode: value })}
          style={{ width: '100%' }}
        >
          {
            radioOption.map(item => <Option key={item.itemCode}>{item.showName}</Option>)
          }
        </Select>
      </Form.Item>,
      onOk: this.handleConfirmChangeType
    });
  };

  handleConfirmChangeType = () => {
    let { selectedData, typeCode } = this.state;
    if (!typeCode) {
      message.error(messages('finance-4.key176')/*请先选择付款方式类型*/)
    } else if (typeCode !== 'ONLINE_PAYMENT' && selectedData.filter(item => item.accountType === 'ALIPAY_LOGON_ID').length) {
      message.error(messages('finance-4.key173')/*所选行中有收款账户为支付宝账户的数据,请返回检查*/)
    } else {
      this.setState({ loading: true });
      paymentService.batchChangeType({
        dataIds: selectedData.map(item => item.id),
        paymentMethod: typeCode
      }).then(() => {
        this.setState({
          typeCode: null,
          loading: false
        }, this.handleRefresh);
      }).catch(e => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
    }
  };

  handleChangeBank = value => {
    this.setState({ bankInfo: value }, this.handleRefresh);
  };

  handleRefresh = () => {
    this.props.onClearSelected(() => this.props.noticeAlert([]));
    this.advancedTableRef.getList();
  };

  handleChangePending = type => {
    Modal.confirm({
      title: type === '02' ? messages('finance-4.key104')/*暂挂*/ : messages('finance-4.key177')/*取消暂挂*/,
      content: type === '02' ? messages('finance-4.key178')/*暂挂后的数据将暂时无法进行支付，将选中数据的暂挂状态批量修改为暂挂？*/ :
        messages('finance-4.key179')/*取消暂挂后的数据将允许进行支付，将选中数据的暂挂状态批量修改为非暂挂？*/,
      onOk: () => this.handleConfirmChangePending(type)
    });
  };

  handleConfirmChangePending = type => {
    let { rowSelection } = this.state;
    this.setState({ loading: true });
    paymentService.batchChangePending({
      dataIds: rowSelection.selectedRowKeys,
      pending: type
    }).then(() => {
      this.setState({ loading: false }, this.handleRefresh);
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    });
  };

  handlePay = () => {
    const { bankInfo, selectedData } = this.state;
    if (!bankInfo) {
      message.error(messages('finance-4.key112')/*不存在有权限的付款账户，无法执行该操作，请确认公司账户授权配置*/);
      return -1;
    }
    if (bankInfo.accountType === 'BANKCARD_ACCOUNT' &&
        selectedData.filter(item => item.accountType === 'ALIPAY_LOGON_ID').length) {
      Modal.error({
        title: messages('finance-4.key113')/*所选行中有收款账户为支付宝账户的数据，请返回检查后再确认支付*/
      });
      return -1;
    }
    let flag = true;
    selectedData.every(item => {
      if (item.currency !== selectedData[0].currency) {
        flag = item.currency === selectedData[0].currency;
        return true;
      }
      return false;
    });
    if (!flag) {
      Modal.error({
        title: messages('finance-4.key416')/*不允许跨币种组批，请重新选择付款数据。*/
      });
      return -1;
    }
    this.setState({ visible: true });
  };

  render() {
    const { radioValue, radioOption, loading, rowSelection, visible, selectedData, buttonDisabled, searchParams,
      errorAlert, tableTitle, searchForm, bankInfo, setOfBookId } = this.state;
    const { getColumns, handleTableTitle, handleTableChange } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={loading}>
          <AdvancedTable
            title={messages('finance-4.key118')/*未支付*/}
            tableName='pay-Unpaid'
            service={this.service}
            searchNotGetList
            tableTitle={() => handleTableTitle(tableTitle, selectedData)}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={searchForm}
            rowKey="id"
            rowSelection={rowSelection}
            columns={getColumns(this.key)}
            onSearch={this.onSearch}
            onChange={handleTableChange}
            pagination={{
              pageSizeOptions: ['20', '50', '100', '150', '200', '500']
            }}
            footer={
              <Space>
                <Button type="primary" disabled={buttonDisabled} onClick={this.handlePay}>
                {radioValue === 'ONLINE_PAYMENT' ? messages('finance-4.key180')/*线上支付*/ :
                  (radioValue === 'OFFLINE_PAYMENT' ? messages('finance-4.key181')/*线下支付*/ : messages('finance-4.key182')/*落地文件支付*/)}
                </Button>
                <Button disabled={selectedData.length === 0} onClick={this.handleChangeType}>
                  {messages('finance-4.key183')/*付款方式类型修改*/}
                </Button>
                <Button disabled={selectedData.length === 0} onClick={() => this.handleChangePending('02')}>
                  {messages('finance-4.key104')/*暂挂*/}
                </Button>
                <Button disabled={selectedData.length === 0} onClick={() => this.handleChangePending('01')}>
                  {messages('finance-4.key177')/*取消暂挂*/}
                </Button>
              </Space>
            }
          >
            <Radio.Group value={radioValue} style={{ marginBottom: '12px' }}
                         onChange={this.onRadioChange}>
              {
                radioOption.map(item => <Radio.Button value={item.itemCode}>{item.showName}</Radio.Button>)
              }
            </Radio.Group>
            <BankHoc
              searchParams={searchParams}
              radioValue={radioValue}
              onRef={ref => this.selectorRef = ref}
              onChangeBank={this.handleChangeBank}
            />
            <div style={{ margin: '12px 0px' }}>
              { errorAlert && <Alert message={errorAlert} type="error" showIcon style={{ width: '100%' }}/> }
            </div>
          </AdvancedTable>
          <PayModal
            radioValue={radioValue}
            visible={visible}
            onCancel={() => { this.setState({ visible: false }) }}
            record={selectedData}
            setOfBookId={setOfBookId}
            onOk={this.handleOk}
            bankInfo={bankInfo}
          />
        </Spin>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default Unpaid;
